<?php
class UsersController extends AppController {

/**
 * Class Name
 *
 * @var string
 */	
	public  $name = 'Users';
/**
 * Use Helpers
 *
 * @var array
 */	
	public $helpers = array('Bayon', 'Follow', 'Bnotice', 'Text', );
	
/**
 * Use component
 * 
 * @var array
 */	
	public $components = array('BayonCaptcha');

	
	public $result = array( 'result' => '',
                            'message' => '',
                            'error' => '',
                            'data' => ''
                            );	
/**
 * Beforefilter is first action run befor other action
 * 
 *
 */
	public function beforeFilter(){
		//echo FULL_BASE_URL;
		parent::beforeFilter();
		 
		$this->__publicActions();
		$this->Auth->allow('*');
		//set style for curent user
		$this->setLayout();
		
		//Start write session of user status
		if($this->Bayon->isLogging() && !$this->Session->read('User.Status')){
        	$this->__writeSessionStatus();
        	$this->__writeSessionAvatar();
        	//set last visit time
        	$this->__setLastVisit();
        	
        }

	}
	
	public function beforeRender() {
        
        $this->set( 'result', $this->result );   
    }
	
/**
 * Admin Coding
 *
 */
	public function admin_index() {
	
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	public function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

	public function admin_add() {
		if (!empty($this->data)) {
			$this->User->create();
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The user has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}

	public function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			
			if(!empty($this->data['User']['new_password'])){
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']);
			}
			
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The user has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}

	public function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for user', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->delete($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('User was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
/**
 * Front End Coding
 * 
 */
    public function captcha( $random = null){
        $this->layout = 'ajax';
       $this->BayonCaptcha->captcha();
        
    }
    public function changeCaptcha(){
       //for ajax only no need add code
    }
    public function checkCaptcha($captcha){
        if($this->BayonCaptcha->validate($captcha)){
            //echo 'Good Captpha :'. $this->Session->read('captcha');
            $this->result = array(
                'error' => 0,
                'result' => 0
            );
        }else{

             $this->result = array(
                'error' => 1,
                'result' => 1,
                 'message' => __('Please try to match the  word shown left', true)
            );
        }
        
    }

    public function checkUser( $username ){
		
		$user = $this->User->find('count',
			array(
				'conditions' => array(
					'User.username' => $username
				)
			)
		);
		return $user;
	}
/**
 * Check email when user signup.
 * This function use for only ajax request
 * 
 * 
 * @param string $email
 */
	public function checkEmail($email){
		if($this->RequestHandler->isAjax()){
			if($this->User->checkField('email', $email)){
				$this->result['error'] = 1;
				$this->result['message'] = sprintf(__('Your email %s already exist please choose another email', true), $email);
			}else{
				$this->result['error'] = 0;
				$this->result['message'] = sprintf(__('Your email %s is available', true), $email);
			}
			
		}else{
			$this->redirect('/');
		}
	}

/**
 * Confirm register
 * 
 */
	public function confirm($code){
		$data = array();
		$confirm = $this->User->find('first', array('conditions' => array('User.confirm_code' => $code), 'recursive' => -1));

		if(!empty($confirm) && ($confirm['User']['confirmed'] == USER_NOT_YET_CONFIRMED)){
			$this->User->id = $confirm['User']['id'];
			$this->User->saveField('confirmed', USER_ALREADY_CONFIRMED);
			
			//prepair login 
			$data['User']['email'] = $confirm['User']['email'];
			$data['User']['password'] = $confirm['User']['password'];
			$this->Auth->login($data);
			
			$this->Session->setFlash(__('<div class="confirm_success"><h2>Your account has been actived.</h2> Now start to setup first your company.</div>', true));
			//$this->set('confirm', USER_NOT_YET_CONFIRMED);
			//redirect 
			$this->redirect(array('controller' => 'company', 'action' => 'create_company'));
			
		}else if(isset($confirm['User']['confirmed']) && ($confirm['User']['confirmed'] == USER_ALREADY_CONFIRMED)){
			
			$this->set('confirm', USER_ALREADY_CONFIRMED);

		}else{
			$this->set('confirm', USER_WRONG_CONFIRM_CODE);
			
		}
		
	}	
/**
 * Check username when user signup.
 * This function use for only ajax request
 * 
 * 
 * @param string $username
 */
	public function checkUsername($username){
		if($this->RequestHandler->isAjax()){
			if($this->reserveKeyword($username)){
				$this->result['error'] = 1;
				$this->result['message'] = sprintf(__('%s already exist please choose another username', true), $username);
			}else{
				if($this->User->checkField('username', $username)){
					$this->result['error'] = 1;
					$this->result['message'] = sprintf(__('%s already exist please choose another username', true), $username);
				}else{
					$this->result['error'] = 0;
					$this->result['message'] = sprintf(__('%s is available', true), $username);
				}
			}
		}else{
			$this->redirect('/');
		}
	}
	public function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The user has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
	}
	
/**
 * follow will return true if this user 
 * following already otherwise false
 *
 * @param string $username
 */
	private function follow( $username ){
		
		$following = $this->User->Friend->find(
			'count',
			array(
				'conditions' => array(
					'Friend.user_id' => $this->Bayon->userId(),
					'Friend.following' => $this->getId( $username ),
				)
			)
		);
		//$following = 1; 
		
		if( $following == 1 ){
			return true;
		}else{
			return false;
		}
	}

/**
 * Get user id by username;
 *
 * @param string $username
 */	
	public function getId( $username ){
		$user = $this->User->find( 
			'first', 
			array( 
				'conditions' => array( 
					'User.username' => $username  
				),
				'fields' => array(
					'User.id'
				) 
			) 
		);
		
		return $user['User']['id'];
	}
/**
 * Index default action of this class 
 * 
 *
 */
	public function index() {

		if($this->Bayon->isLogging()){
                        $currentId = $this->Bayon->userId();
			//lastest notice
                        $latest = $this->User->Notice->latestNotice($currentId);
			
			$friends_id = implode(',',$this->User->Friend->getFollowing($this->Bayon->userId())); 
			if($friends_id)
				$friends_id = $friends_id.', '.$this->Bayon->userId(); 
			else 
				$friends_id = $this->Bayon->userId(); 
				
			//set up paginate for display notice
			$this->paginate = array(
                            'conditions' => array(
		        	'Notice.user_id IN ('.$friends_id.')',
				'Notice.status' => BAYON_NOTICE_STATUS_PUBLISHED
				),
                            'limit' => 15,
                            'recursive' => 1,
                            'fields' => $this->__noticeFields(),
                            'order' => 'Notice.id DESC'
                        );
                        $notices = $this->paginate('Notice');

                     //init to include user avatar
                    $i = 0;
                    $aNotices = array();
                    foreach($notices as $notice){
                        $aNotices[$i] = $notice;
                        $aNotices[$i]['avatar'] = $this->User->Avatar->getAvatar($notice['User']['id'], AVATAR_WIDHT_48);
                        $i++;
                    }
                    $this->set('notices', $aNotices );
                    $this->set('latest', $latest);
            }
	}
        private function __noticeFields(){
            $noticeFields =array(
                'User.id',
                'User.name',
                'User.username',
                'User.email',
                'Notice.id',
                'Notice.message',
                'Notice.render',
                'Notice.reply_to',
                'Notice.repeat_of',
                'Notice.source',
                'Notice.user_id',
                'Notice.created',
                
            );
            return $noticeFields;
        }

/**
 * User login
 * 
 */
	public function login(){
            if(!empty($this->data)){
                $this->Session->setFlash('Invalid User name or passowrd. Please try again!');
            }else{
                if ($this->Session->read( 'Auth.User' )) {
                    //$this->Session->setFlash( __( 'You are logged in!', true ) );
                    $this->redirect( '/', null, false );
		}
            }
	}
/**
 * User logout
 * 
 */
	public  function logout(){
		$this->Session->delete('User.Status');
		$this->Session->setFlash('Good-Bye');
		$this->redirect($this->Auth->logout());
		$this->Session->delete('User.Status');
		
	}
	
/**
 * Display user profile
 */	
	public function profile(){
		$this->layout = 'user';
                //pr($this->params['username']); die();
                if(isset( $this->params['username'] )){
                    $username = $this->params['username'];
                    $this->set('username', $username);
                }else{
                     $this->redirect('/');
                }

		if( isset( $username ) ){
			
			$this->set('username', $username);
			$this->set( 'currentUser', false);
			$this->set( 'existUser', true);
			
			if( $this->checkUser($username) ){
				if( $username === $this->Bayon->username()){
					//if view user view his/her profile
					$this->set( 'currentUser', true );
					$noticeUserId = $this->Bayon->userId();
					
				}else {
					$this->layout = 'user';
					$noticeUserId = $this->getId( $username );
					$this->set( 'following', $this->follow( $username ) );
					$this->set( 'friend_id', $noticeUserId );
					
				}
				
				//setup pagination
				$this->paginate = array(
			        'conditions' => array(
						'Notice.user_id' => $noticeUserId,
						'Notice.status' => BAYON_NOTICE_STATUS_PUBLISHED
					),
			        'limit' => 15,
				'recursive' => 1,
				'order' => 'Notice.id DESC'
	    		);

                        $this->set('avatar', $this->User->Avatar->getAvatar($noticeUserId, AVATAR_WIDHT_96));
	    		$notices = $this->paginate('Notice');
                         //init to include user avatar
                        $i = 0;
                        $aNotices = array();
                        foreach($notices as $notice){
                            $aNotices[$i] = $notice;
                            $aNotices[$i]['avatar'] = $this->User->Avatar->getAvatar($notice['User']['id'], AVATAR_WIDHT_48);
                            $i++;
                        }
                        $this->set('notices', $aNotices );
	    		
			}else{
				$this->set( 'existUser', false);
			}
		}
	}
	
/**
 * User signup function
 *
 */
	public function signup(){
		
		if ($this->Bayon->isGuest()){
			if (!empty($this->data)) {
				//set more properties when user signup
				$this->data['User']['group_id'] = $this->User->Group->getGroupId(GROUP_REGISTER);
				//$this->data['User']['confirm_code'] = String::uuid();
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['text_password']);
				$this->data['User']['register_date'] = date('Y-m-d h:i:s');
				$this->data['User']['last_login'] = date('Y-m-d h:i:s');
                                $day = $this->data['User']['day'];
                                $month = $this->data['User']['month'];
                                $year = $this->data['User']['year'];
                                $this->data['User']['dob'] = sprintf('%s-%s-%s', $year, $month, $day);
				
				//temporary active
				$this->data['User']['confirmed'] = 0;
				
				$this->User->create();
				if ($this->User->save($this->data)) {
					$userId = $this->User->id;
					//sent mail confirm 
					$this->__sentConfirmRegister($userId, $this->data);

                                        //write session of email
                                        $this->Session->write('email', $this->data['User']['email']);
					
					//create user status
					$status = array(
							 0 => array(
								'UserStatus' => array(
								'user_id' => $userId,
								'name_field' => BAYON_FOLLOWER,
								'value' => 0,					
								)
							),
							1 => array(
								'UserStatus' => array(
								'user_id' => $userId,
								'name_field' => BAYON_FOLLOWING,
								'value' => 0,					
								)
							),
							2 => array(
								'UserStatus' => array(
								'user_id' => $userId,
								'name_field' => STATUS_NOTICE,
								'value' => 0,					
								)
							),
							3 => array(
								'UserStatus' => array(
								'user_id' => $userId,
								'name_field' => STATUS_COMPANY,
								'value' => 0,					
								)
							),
							4 => array(
								'UserStatus' => array(
								'user_id' => $userId,
								'name_field' => STATUS_PROGRESS,
								'value' => 0,					
								)
							)
						);
					//$this->loadModel('UserStatus');
					$this->User->UserStatus->create();
					$this->User->UserStatus->saveAll($status);
					
					$this->Session->setFlash(__('The user has been saved', true));
					$this->redirect(array('action' => 'confirmSignup'));
				} else {
					$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
				}
			}
		}else{
			//redirect to home page
			$this->redirect('/'); 
		}
	}

        public function confirmSignup(){
            $email = $this->Session->read('email');
            if($email){
                $this->set('email', $email);
            }else{
                $this->redirect('/');
            }
        }
	
/**
 * get user status that contain number of following, follower, notice, ...
 * 
 *  @param int $user_id
 *  
 */
	public function status( $user_id, $status = null ){
		if($status){
			return $this->User->UserStatus->status($user_id, $status);
		}else{
			return $this->User->UserStatus->status($user_id);
		}
		
	}	
/**
 * View 
 *
 * @param int $id
 */
	public function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

        public function testEmail(){
            //sent mail below
                $subject = __('Test Sent Email', true);
                $link = FULL_BASE_URL.$this->base.'/users/confirm/'. 1246;
                $link = sprintf('<a href="%s"> %s </a>', $link, $link);
                $message = sprintf("Howdy, <br/>
                            <p>Thank you for signing up with Bayonpage.com.</p>
                            <p> Please click this link to activate your registration:</p>
                            <p> %s</p>
                            --The Bayonpage.com Team
                            (If clicking the link in this message does not work, copy and paste it into the address bar of your browser.)", $link);
		
                $this->sendNewUserMail('notification@bayonpage.com  ', 'sophy.prak@gmail.com', $subject, $message);
                die('Your email has been sent');
           
        }

        /**
 * SECTION LOCAL FUNCTION
 * 
 * 
 * @param unknown_type $userId
 * @param unknown_type $email
 */	
	private function __sentConfirmRegister($userId, $data){
		$confirmCode = $this->Auth->password($data['User']['email'].$userId);
		$this->User->id = $userId;
		$this->User->saveField('confirm_code', $confirmCode);
		
		//sent mail below
                $subject = __('Confirm Your Register', true);
                $link = FULL_BASE_URL.$this->base.'/users/confirm/'.$confirmCode;
                $link = sprintf('<a href="%s"> %s </a>', $link, $link);
                $message = sprintf("Howdy,

                            Thank you for signing up with Bayonpage.com.

                            Please click this link to activate your registration:

                             %s 

                            --The Bayonpage.com Team

                            (If clicking the link in this message does not work, copy and paste it into the address bar of your browser.)", $link);
		//$this->sentEmail();
                $this->sendNewUserMail('notification@bayonpage.com  ', $data['User']['email'], $subject, $message);
	}
	private function __setLastVisit(){
		$user_id = $this->Auth->user('id');
		$this->User->id = $user_id;
		$this->User->saveField('last_visit', date('Y-m-d h:i:s'));
	}
/**
 * Write session of user status
 * 
 */	
	private function __writeSessionStatus(){
		
		$this->Session->write('User.Status', $this->status( $this->Bayon->userId() ));
	}
	
/**
 * Write session of user's avatar
 * 
 */
	private function __writeSessionAvatar(){
		$avatars = $this->User->Avatar->getAllAvatars($this->Bayon->userId());
		$avatarNew = '';
		foreach($avatars as $av){
			$avatarNew[$av['Avatar']['height']] = $av;
			
		}
		
		$this->Session->write('User.Avatar', $avatarNew);
	}
	
	
	private function __publicActions(){
		 $this->Auth->allowedActions = array(
		 	'logout', 'login', 'index', 'profile', 'signup', 'status', 'checkUsername', 'checkEmail', 'confirm'
		 	
		 );
                 
	}

       
}
?>